package com.centling.smartSealForPhone.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.bean.LoginBean;
import com.centling.smartSealForPhone.constants.GlobalData;
import com.centling.smartSealForPhone.constants.SPConstants;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.wsdk.service.BluetoothLeService;
import com.centling.smartSealForPhone.utils.BlueToothScanUtil;
import com.centling.smartSealForPhone.utils.ControlUtil;
import com.centling.smartSealForPhone.utils.OkHttpUtil;
import com.centling.smartSealForPhone.utils.ParseBluetoothData;
import com.centling.smartSealForPhone.utils.SPUtil;
import com.centling.smartSealForPhone.utils.ShowDialog;
import com.centling.smartSealForPhone.utils.ShowToast;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;

public class GuideActivity
        extends BaseActivity
        implements BlueToothScanUtil.StopSearchListener {
    private static final int OPEN_BLUE_DIALOG = 1000;

    private TextView mTvTitle;
    private TextView mTvGuide;
    private TextView mBtnNext;
    private ImageView guidIvDesc;

    private int step = 1;

    private String macAddress = "";

    private BlueToothScanUtil blueToothScanUtil;

    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                mProcessDialog.dismiss();
                if (BuildConfig.DEBUG) {
                    ShowToast.shortTime("Guide Connected");
                }
                GlobalData.isConnect = true;
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                BluetoothDevice connectedDevice = intent.getParcelableExtra("BLUETOOTH_DEVICE");
                ShowToast.shortTime( "智能印章断开连接");
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                if (ParseBluetoothData.isChangeStamp(data)) {
                    new ControlUtil().lock();
                } else if (ParseBluetoothData.parseLock(data)) {
                    if (step == 1) {
                        mTvTitle.setVisibility(View.INVISIBLE);
                        mTvGuide.setText("请添加印油完成后点击确定\n");
                        mBtnNext.setText("确定");
                        guidIvDesc.setImageDrawable(
                                ContextCompat.getDrawable(mContext, R.drawable.ic_guide2));
                    }
                    step++;
                }
            }
        }
    };

    private void updateMacAddress() {
        Map<String, String> params = new HashMap<>(1);
        params.put("blueToothMac", macAddress);
        postJsonEnqueue(UrlConstants.UPLOAD_MAC_ADDRESS, params,
                new OkHttpUtil.NetCallBack() {
                    @Override
                    public void onSucceed(String json) {
                        Gson gson = new Gson();
                        ShowToast.shortTime("地址上传成功");
                        Intent intentMain = new Intent(mContext,
                                MainTabsActivity.class);
                        LoginBean loginBean = gson.fromJson(
                                SPUtil.getString(SPConstants.LOGIN_JSON),
                                LoginBean.class);
                        loginBean.getEquipRegisterInfo().setEquipStatus("0");
                        loginBean.getEquipRegisterInfo().setBlueToothMac(
                                macAddress);
                        SPUtil.setString(SPConstants.LOGIN_JSON,
                                gson.toJson(loginBean, LoginBean.class));
                        intentMain.putExtra("loginbean", loginBean);
                        startActivity(intentMain);
                        finish();
                    }

                    @Override
                    public void onFailed(String reason) {
                        ShowToast.shortTime("网络连接错误,未能上传Mac地址");
                    }
                });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);

        macAddress = getIntent().getStringExtra("macAddress");
        if (TextUtils.isEmpty(macAddress)) {
            ShowToast.shortTime("获取设备MAC地址失败");
            finish();
        }

        mTvTitle = findViewById(R.id.guide_tv_title);
        mTvGuide = findViewById(R.id.guide_tv_guide);
        mBtnNext = findViewById(R.id.guide_btn_next);
        guidIvDesc = findViewById(R.id.guid_iv_desc);

        mBtnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!BlueToothScanUtil.isBlueToothOpened()) {
                    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, OPEN_BLUE_DIALOG);
                    return;
                }
                switch (step) {
                    case 1:
                        if (GlobalData.isConnect) {
                            new ControlUtil().cancelChangeStamp();
                        } else {
                            ShowDialog.showSelectDialog(mContext, "重新连接蓝牙", "蓝牙未连接，请先连接蓝牙", "",
                                    new View.OnClickListener() {

                                        @Override
                                        public void onClick(View v) {
                                            mProcessDialog.setTitle("正在连接蓝牙").showNormal();
                                            blueToothScanUtil.setMacAddress(macAddress);
                                            blueToothScanUtil.startSearchBlueDevice();
                                            blueToothScanUtil.setStopSearchListener(
                                                    GuideActivity.this);
                                        }
                                    });
                        }
                        break;
                    default:
                        if (step >= 2) {
                            step = 3;
                            if (GlobalData.isConnect) {
                                updateMacAddress();
                            } else {
                                ShowDialog.showSelectDialog(mContext, "重新连接蓝牙", "蓝牙未连接，请先连接蓝牙", "",
                                        new View.OnClickListener() {

                                            @Override
                                            public void onClick(View v) {
                                                mProcessDialog.setTitle("正在连接蓝牙").showNormal();
                                                blueToothScanUtil.setMacAddress(macAddress);
                                                blueToothScanUtil.startSearchBlueDevice();
                                                blueToothScanUtil.setStopSearchListener(
                                                        GuideActivity.this);
                                            }
                                        });
                            }
                        }
                        break;
                }
            }
        });

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        registerReceiver(bluetoothReceiver, intentFilter);

        blueToothScanUtil = new BlueToothScanUtil(mContext);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!BlueToothScanUtil.isBlueToothOpened()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, OPEN_BLUE_DIALOG);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(bluetoothReceiver);
            BluetoothLeService.disconnect();
        } catch (Exception ignored) {
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OPEN_BLUE_DIALOG && resultCode == Activity.RESULT_CANCELED) {
            ShowToast.shortTime("继续操作需要开启蓝牙");
            finish();
        }
    }

    @Override
    public void onBackPressed() {

    }

    @Override
    public void onStopped(boolean timeout) {
        mProcessDialog.dismiss();
        if(timeout) {
            ShowToast.shortTime("连接设备失败");
        }
    }
}
